package com.fh.shop.service.impl;/**
 * 描述:
 * Author:袁亚强
 * Date:2021/12/2214:43
 */

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.Shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fh.common.baseData.CommonData;
import com.fh.common.baseData.TableData;
import com.fh.common.baseData.TableParams;
import com.fh.common.exceptions.CountException;
import com.fh.common.exceptions.ParamException;
import com.fh.shop.entity.po.*;
import com.fh.shop.mapper.OrderInfoMapper;
import com.fh.shop.mapper.OrderMapper;
import com.fh.shop.mapper.ShopMapper;
import com.fh.shop.mapper.ShopValuesMapper;
import com.fh.shop.service.OrderService;
import com.fh.user.entity.vo.User;
import com.fh.utils.IDUNIQUE;
import com.fh.utils.TestPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * created by macro on 2021/12/22,
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private ShopValuesMapper shopValuesMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public String createOrder(Order order) {
        //构建订单对象
        Order o=new Order();
        //生成一个订单号
        o.setId(IDUNIQUE.uniqueLong()+"");
        //构建订单详情对象
        List<OrderInfo> os=new ArrayList<>();

        Date now=new Date();
        if (order.getAid() == null) {
            throw new ParamException();
        }

        User u = (User) request.getAttribute("u");
        Double totalMoney = 0.0;
        List<CarData> carDataList = (List<CarData>) redisTemplate.opsForHash().get(CommonData.REDIS_KEY + CommonData.REDIS_PRO, u.getName());

        //创建购物车没有被选中的商品
        List<CarData> carDataList2 = new ArrayList<>();
        for (int i = 0; i < carDataList.size(); i++) {
            CarData carData = carDataList.get(i);
            if (carData.getIsChecked() == 0) {
                Integer count = 0;
                if (carData.getSid() != null) {
                    ShopValues shopValues = shopValuesMapper.selectById(carData.getSid());
                    JSONObject parse = (JSONObject) JSONObject.parse(shopValues.getValuess());
                    count = parse.getInteger("count");
                    if (count < carData.getCount()) {
                        throw new CountException(carData.getTitle() + carData.getId() + "    库存不足");
                    }
                    //更新库存
                    parse.put("count", count - carData.getCount());
                    shopValues.setValuess(parse.toJSONString());
                    //更新数据
                    shopValuesMapper.updateById(shopValues);
                } else {
                    ShopBean shopBean = shopMapper.selectById(carData.getId());
                    count = shopBean.getRemarks();
                    //判断库存
                    if (count < carData.getCount()) {
                        throw new CountException(carData.getTitle() + carData.getId() + "库存不足");
                    }
                    //更新库存
                    shopBean.setRemarks(count - carData.getCount());
                    shopMapper.updateById(shopBean);
                }
                totalMoney += carData.getPrice() * carData.getCount();
                OrderInfo one = new OrderInfo();
                one.setOid(o.getId());
                one.setCreateDate(now);
                one.setCount(carData.getCount());
                one.setPrice(carData.getPrice());
                one.setPid(carData.getId());
                one.setSid(carData.getSid());
              //  orderInfoMapper.insert(one);
                os.add(one);
            } else {
                carDataList2.add(carData);
            }
        }
        orderInfoMapper.addOrderInfo(os);
        o.setCreateDate(now);
        o.setTotalMoney(totalMoney);
        o.setAid(order.getAid());
        o.setRemark(order.getRemark());
        orderMapper.insert(o);
        redisTemplate.opsForHash().put(CommonData.REDIS_KEY + CommonData.REDIS_PRO, u.getName(),carDataList2);
        return o.getId();
    }

    @Override
    public String getUrl(String oid) {
        String url="";
        //验参
        if(StringUtils.isEmpty(oid)){
            throw new ParamException();
        }
        //先查redis 看看之前是否已经生成过此订单的二维码   key 有失效时间了
        String o = (String) redisTemplate.opsForValue().get(oid + CommonData.REDIS_PRO);
        if(o!=null){
            return o;
        }
        //得到订单信息
        Order order = orderMapper.selectById(oid);
        //调用支付接口
        if(order.getPayType()==0){//调支付宝接口
            try {
                url= TestPay.ceatePay(oid, "飞狐电商订单", order.getTotalMoney());
                //放入redis
                redisTemplate.opsForValue().set(oid + CommonData.REDIS_PRO,url,10*60, TimeUnit.SECONDS);
            } catch (AlipayApiException e) {
                e.printStackTrace();
                throw new RuntimeException("调用阿里支付接口异常");
            }
        }else if(order.getPayType()==1){
            //调微信接口
        }else {
            throw new ParamException();
        }
        return url;
    }

    @Override
    public Integer qeuryOid(String oid) {
        Integer b = 0;
        String s = "";
        if(StringUtils.isEmpty(oid)){
            throw new ParamException();
        }
        Order order = orderMapper.selectById(oid);
        try {
             s = TestPay.queyrStatu(oid);
            if (s == null) {
                order.setPayStatus(4);
                orderMapper.updateById(order);
                b= 4;// 交易等待中
            }
            if (s.equals("TRADE_SUCCESS")) {
                order.setPayStatus(1);
                orderMapper.updateById(order);
                b= 1;// 交易成功
            } else if (s.equals("TRADE_FINISHED")) {
                order.setPayStatus(2);
                orderMapper.updateById(order);
                b= 2;//交易结束
            } else if (s.equals("WAIT_BUYER_PAY")) {
                order.setPayStatus(3);
                orderMapper.updateById(order);
                b= 3;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return b;
    }

    @Override
    public TableData<Order> queryPage(TableParams params) {
        TableData<Order> rs=new TableData<>();
        if(params.getPage()==null||params.getSize()==null){
            throw new ParamException();
        }

        IPage<Order> page=new Page<>(params.getPage(),params.getSize());
        IPage<Order> orderIPage = orderMapper.selectPage(page,null);
        rs.setCount(orderIPage.getTotal());
        rs.setRows(orderIPage.getRecords());
        return rs;
    }

    @Override
    public void del(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new ParamException();
        }
        orderMapper.deleteById(id);
    }

    @Override
    public List<OrderInfo> queryByOid(String oid) {
        if (StringUtils.isEmpty(oid)) {
            throw new ParamException();
        }

        QueryWrapper<OrderInfo> where = new QueryWrapper<>();
        where.eq("oid", oid);
        return orderInfoMapper.selectList(where);
    }

}
